#include "DeviceModel.h"
#include "services/DatabaseService.h"
#include "utils/Logger.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

DeviceModel::DeviceModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

DeviceModel::~DeviceModel()
{
}

// 返回行数
int DeviceModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_devices.count();
}

// 返回数据
QVariant DeviceModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_devices.count())
        return QVariant();

    const Device &device = m_devices.at(index.row());

    switch (role)
    {
    case DeviceIdRole:
        return device.deviceId();
    case DeviceNameRole:
        return device.deviceName();
    case IpAddressRole:
        return device.ipAddress();
    case PortRole:
        return device.port();
    case SlaveIdRole:
        return device.slaveId();
    case StatusRole:
        return device.status();
    case LastUpdateRole:
        return device.lastUpdate().toString("yyyy-MM-dd HH:mm:ss");
    case DescriptionRole:
        return device.description();
    default:
        return QVariant();
    }
}

// 角色名称映射（QML 中使用）
QHash<int, QByteArray> DeviceModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[DeviceIdRole] = "deviceId";
    roles[DeviceNameRole] = "deviceName";
    roles[IpAddressRole] = "ipAddress";
    roles[PortRole] = "port";
    roles[SlaveIdRole] = "slaveId";
    roles[StatusRole] = "status";
    roles[LastUpdateRole] = "lastUpdate";
    roles[DescriptionRole] = "description";
    return roles;
}

// 从数据库加载设备列表
bool DeviceModel::loadFromDatabase()
{
    qInfo() << "DeviceModel: 从数据库加载设备列表";

    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    if (!query.exec("SELECT device_id, device_name, ip_address, port, slave_id, "
                    "status, last_update, description FROM devices ORDER BY created_at"))
    {
        qWarning() << "DeviceModel: 查询失败:" << query.lastError().text();
        return false;
    }

    // 清空现有数据
    beginResetModel();
    m_devices.clear();

    // 加载数据
    while (query.next())
    {
        Device device;
        device.setDeviceId(query.value(0).toString());
        device.setDeviceName(query.value(1).toString());
        device.setIpAddress(query.value(2).toString());
        device.setPort(query.value(3).toInt());
        device.setSlaveId(query.value(4).toInt());
        device.setStatus(query.value(5).toString());
        device.setLastUpdate(query.value(6).toDateTime());
        device.setDescription(query.value(7).toString());

        m_devices.append(device);
    }

    endResetModel();
    emit countChanged();

    qInfo() << "DeviceModel: 加载完成，共" << m_devices.count() << "个设备";
    return true;
}

// 添加设备
bool DeviceModel::addDevice(const QString &deviceId,
                            const QString &deviceName,
                            const QString &ipAddress,
                            int port,
                            int slaveId,
                            const QString &description)
{
    // 检查设备ID是否已存在
    if (deviceExists(deviceId))
    {
        qWarning() << "DeviceModel: 设备ID已存在:" << deviceId;
        return false;
    }

    // 创建设备对象
    Device device(deviceId, deviceName, ipAddress);
    device.setPort(port);
    device.setSlaveId(slaveId);
    device.setDescription(description);

    // 保存到数据库
    if (!saveToDatabase(device))
    {
        return false;
    }

    // 添加到模型
    beginInsertRows(QModelIndex(), m_devices.count(), m_devices.count());
    m_devices.append(device);
    endInsertRows();

    emit countChanged();
    emit deviceAdded(deviceId);

    // 记录日志
    Logger::instance()->logOperation("add_device", deviceId,
                                     QString("添加设备: %1").arg(deviceName));

    qInfo() << "DeviceModel: 添加设备成功:" << deviceId;
    return true;
}

// 删除设备
bool DeviceModel::removeDevice(const QString &deviceId)
{
    int index = findDeviceIndex(deviceId);
    if (index < 0)
    {
        qWarning() << "DeviceModel: 设备不存在:" << deviceId;
        return false;
    }

    return removeDeviceAt(index);
}

// 根据索引删除设备
bool DeviceModel::removeDeviceAt(int index)
{
    if (index < 0 || index >= m_devices.count())
    {
        qWarning() << "DeviceModel: 索引越界:" << index;
        return false;
    }

    const Device &device = m_devices.at(index);
    QString deviceId = device.deviceId();

    // 从数据库删除
    if (!deleteFromDatabase(deviceId))
    {
        return false;
    }

    // 从模型删除
    beginRemoveRows(QModelIndex(), index, index);
    m_devices.removeAt(index);
    endRemoveRows();

    emit countChanged();
    emit deviceRemoved(deviceId);

    // 记录日志
    Logger::instance()->logOperation("delete_device", deviceId, "删除设备");

    qInfo() << "DeviceModel: 删除设备成功:" << deviceId;
    return true;
}

// 更新设备信息
bool DeviceModel::updateDevice(const QString &deviceId,
                               const QString &deviceName,
                               const QString &ipAddress,
                               int port,
                               int slaveId,
                               const QString &description)
{
    int index = findDeviceIndex(deviceId);
    if (index < 0)
    {
        qWarning() << "DeviceModel: 设备不存在:" << deviceId;
        return false;
    }

    // 更新设备对象
    Device &device = m_devices[index];
    device.setDeviceName(deviceName);
    device.setIpAddress(ipAddress);
    device.setPort(port);
    device.setSlaveId(slaveId);
    device.setDescription(description);

    // 保存到数据库
    if (!saveToDatabase(device))
    {
        return false;
    }

    // 通知模型更新
    QModelIndex modelIndex = createIndex(index, 0);
    emit dataChanged(modelIndex, modelIndex);
    emit deviceUpdated(deviceId);

    // 记录日志
    Logger::instance()->logOperation("update_device", deviceId, "更新设备信息");

    qInfo() << "DeviceModel: 更新设备成功:" << deviceId;
    return true;
}

// 更新设备状态
bool DeviceModel::updateDeviceStatus(const QString &deviceId, const QString &status)
{
    int index = findDeviceIndex(deviceId);
    if (index < 0)
    {
        return false;
    }

    // 更新状态
    Device &device = m_devices[index];
    device.setStatus(status);
    device.setLastUpdate(QDateTime::currentDateTime());

    // 更新数据库
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);
    query.prepare("UPDATE devices SET status = ?, last_update = datetime('now', 'localtime') WHERE device_id = ?");
    query.addBindValue(status);
    query.addBindValue(deviceId);

    if (!query.exec())
    {
        qWarning() << "DeviceModel: 更新状态失败:" << query.lastError().text();
        return false;
    }

    // 通知模型更新
    QModelIndex modelIndex = createIndex(index, 0);
    emit dataChanged(modelIndex, modelIndex);

    return true;
}

// 获取设备（根据索引）
Device DeviceModel::getDevice(int index) const
{
    if (index >= 0 && index < m_devices.count())
    {
        return m_devices.at(index);
    }
    return Device();
}

// 获取设备（根据ID）
Device DeviceModel::getDeviceById(const QString &deviceId) const
{
    int index = findDeviceIndex(deviceId);
    if (index >= 0)
    {
        return m_devices.at(index);
    }
    return Device();
}

// 查找设备索引
int DeviceModel::findDeviceIndex(const QString &deviceId) const
{
    for (int i = 0; i < m_devices.count(); ++i)
    {
        if (m_devices.at(i).deviceId() == deviceId)
        {
            return i;
        }
    }
    return -1;
}

// 检查设备是否存在
bool DeviceModel::deviceExists(const QString &deviceId) const
{
    return findDeviceIndex(deviceId) >= 0;
}

// 获取在线设备数量
int DeviceModel::getOnlineCount() const
{
    int count = 0;
    for (const Device &device : m_devices)
    {
        if (device.status() == "online")
        {
            count++;
        }
    }
    return count;
}

// 清空列表
void DeviceModel::clear()
{
    beginResetModel();
    m_devices.clear();
    endResetModel();
    emit countChanged();
}

// 保存设备到数据库
bool DeviceModel::saveToDatabase(const Device &device)
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    query.prepare(R"(
        INSERT OR REPLACE INTO devices 
        (device_id, device_name, ip_address, port, slave_id, status, description)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    )");

    query.addBindValue(device.deviceId());
    query.addBindValue(device.deviceName());
    query.addBindValue(device.ipAddress());
    query.addBindValue(device.port());
    query.addBindValue(device.slaveId());
    query.addBindValue(device.status());
    query.addBindValue(device.description());

    if (!query.exec())
    {
        qWarning() << "DeviceModel: 保存失败:" << query.lastError().text();
        return false;
    }

    return true;
}

// 从数据库删除设备
bool DeviceModel::deleteFromDatabase(const QString &deviceId)
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    query.prepare("DELETE FROM devices WHERE device_id = ?");
    query.addBindValue(deviceId);

    if (!query.exec())
    {
        qWarning() << "DeviceModel: 删除失败:" << query.lastError().text();
        return false;
    }

    return true;
}
